package com.tmobile.book.matmataytang;

import java.util.ArrayList;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;


public class MainActivity extends FragmentActivity {

	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	private static final String TAG = "MainActivity";
	private static ArrayList<String> chapterContent;
	private SharedPreferences mPref;
	private Editor editor;
	private static float fontSize;
	ChapterFragment fragment;
	private int bookmarkedSpine, selectedSpine;
	View backPressedView, layoutView;
	PopupWindow backPressedPopup;
	boolean showRatePopup = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		layoutView = findViewById(R.id.drawer_layout);
		backPressedView = getLayoutInflater().inflate(
				R.layout.back_pressed_popup, null);
		chapterContent = AppSingleton.getInstance().getChapterContent();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);
		mPref = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		editor = mPref.edit();
		fontSize = mPref.getFloat(Constants.PREF_FONT_SIZE, 16);
		// Set the adapter for the list view
		mDrawerList.setAdapter(new ArrayAdapter<String>(this,
				R.layout.drawer_list_item, Constants.spines));
		// Set the list's click listener
		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
		mTitle = mDrawerTitle = getTitle();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {

			/** Called when a drawer has settled in a completely closed state. */
			public void onDrawerClosed(View view) {
				super.onDrawerClosed(view);
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}

			/** Called when a drawer has settled in a completely open state. */
			public void onDrawerOpened(View drawerView) {
				super.onDrawerOpened(drawerView);
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}
		};

		// Set the drawer toggle as the DrawerListener
		mDrawerLayout.setDrawerListener(mDrawerToggle);		
		if (savedInstanceState == null) {
			bookmarkedSpine = mPref.getInt(Constants.PREF_BOOKMARK_SPINE, 0);
			selectItem(bookmarkedSpine);
		}
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
//		mDrawerLayout.openDrawer(Gravity.LEFT);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		Log.i(TAG, "onBackPressed");
		showRatePopup = mPref.getBoolean(Constants.PREF_SHOW_RATE_POPUP, true);
		if(!showRatePopup){
			finish();
			return;
		}
		backPressedPopup = new PopupWindow(backPressedView,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
		backPressedPopup
				.showAtLocation(backPressedView, Gravity.CENTER, 50, 50);
		Button rateButton = (Button) backPressedView
				.findViewById(R.id.rateButton);
		Button laterButton = (Button) backPressedView
				.findViewById(R.id.laterButton);
		Button neverButton = (Button) backPressedView
				.findViewById(R.id.neverButton);
		
		rateButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				backPressedPopup.dismiss();
				showRatePopup = false;
				editor.putBoolean(Constants.PREF_SHOW_RATE_POPUP, false);
				editor.commit();
				final String appPackageName = getPackageName(); // getPackageName()
																// from Context
																// or Activity
																// object
				try {
					startActivity(new Intent(Intent.ACTION_VIEW, Uri
							.parse("market://details?id=" + appPackageName)));
				} catch (ActivityNotFoundException anfe) {
					startActivity(new Intent(
							Intent.ACTION_VIEW,
							Uri.parse("http://play.google.com/store/apps/details?id="
									+ appPackageName)));
				}
				finish();
			}
		});
		laterButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				backPressedPopup.dismiss();
				finish();
			}
		});
		neverButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				backPressedPopup.dismiss();
				showRatePopup = false;
				editor.putBoolean(Constants.PREF_SHOW_RATE_POPUP, false);
				editor.commit();
				finish();
			}
		});
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/* Called whenever we call invalidateOptionsMenu() */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// If the nav drawer is open, hide action items related to the content
		// view
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.increase_font).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle action buttons
		switch (item.getItemId()) {
		case R.id.increase_font:
			// create intent to perform web search for this planet
			fontSize += 2;
			editor.putFloat(Constants.PREF_FONT_SIZE, fontSize);
			editor.commit();
			fragment.onResume();
			return true;

		case R.id.decrease_font:
			fontSize -= 2;
			editor.putFloat(Constants.PREF_FONT_SIZE, fontSize);
			editor.commit();
			fragment.onResume();
			return true;

		case R.id.bookmark:
			bookmarkedSpine = selectedSpine;
			editor.putInt(Constants.PREF_BOOKMARK_SPINE, bookmarkedSpine);
			editor.commit();
			Toast.makeText(
					getApplicationContext(),
					getString(R.string.bookmarked) + " "
							+ Constants.spines[selectedSpine],
					Toast.LENGTH_SHORT).show();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}	

	WebView webview;
	int i = 0;	

	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView parent, View view, int position,
				long id) {
			selectItem(position);
		}
	}

	/** Swaps fragments in the main content view */
	private void selectItem(int position) {
		// Create a new fragment and specify the chapter to show based on
		// position
		fragment = new ChapterFragment();
		Bundle args = new Bundle();
		args.putInt(ChapterFragment.ARG_CHAPTER_NUMBER, position);
		fragment.setArguments(args);
		// Insert the fragment by replacing any existing fragment
		FragmentManager fragmentManager = getSupportFragmentManager();
		fragmentManager.beginTransaction()
				.replace(R.id.content_frame, fragment).commit();

		// Highlight the selected item, update the title, and close the drawer
		mDrawerList.setItemChecked(position, true);
		setTitle(Constants.spines[position]);
		mDrawerLayout.closeDrawer(mDrawerList);
		selectedSpine = position;
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	/**
	 * Fragment that appears in the "content_frame", shows a chapter
	 */
	public static class ChapterFragment extends Fragment {
		public static final String ARG_CHAPTER_NUMBER = "chapter_number";
		private TextView textView;
		int chapterIndex;
		AdView adviewHeader, adViewFooter;
		public ChapterFragment() {
			// Empty constructor required for fragment subclasses
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_chapter,
					container, false);
			textView = (TextView) rootView.findViewById(R.id.content);
			chapterIndex = getArguments().getInt(ARG_CHAPTER_NUMBER);
			String chapter = Constants.spines[chapterIndex];
			adViewFooter = (AdView) rootView.findViewById(R.id.adViewFooter);
			adviewHeader = (AdView) rootView.findViewById(R.id.adViewHeader);
			adViewFooter.loadAd(new AdRequest.Builder().addTestDevice(
					"BAE35FE965DED90D640AFB2155F2A139").build());
			adviewHeader.loadAd(new AdRequest.Builder().addTestDevice(
					"BAE35FE965DED90D640AFB2155F2A139").build());
			getActivity().setTitle(chapter);
			return rootView;
		}

		@Override
		public void onResume() {
			super.onResume();
			adViewFooter.resume();
			adviewHeader.resume();
			textView.setTextSize(fontSize);
			String sb = chapterContent.get(chapterIndex);
			if (sb != null) {
				// Log.d(TAG, sb);
				textView.setText(Html.fromHtml(sb));
				// webView.loadDataWithBaseURL("", sb, "text/html", "UTF-8",
				// "");
			}
		}

		@Override
		public void onDestroy() {
			super.onDestroy();
			adViewFooter.destroy();
			adviewHeader.destroy();
		}

		@Override
		public void onPause() {
			super.onPause();
			adViewFooter.pause();
			adviewHeader.pause();
		}
		

		// ////////////
	}
}
